class Cpanel::GridsController < Cpanel::BaseController
  before_action :set_grid, only: [:show, :edit, :update, :destroy]

  def index
    respond_to do |format|
      format.html
      format.json { render json: GridsDatatable.new(view_context, current_admin) }
    end
  end

  def show; end

  def new
    @grid = Grid.new
  end

  def edit; end

  def create
    @grid = Grid.new(grid_params)

    respond_to do |format|
      if @grid.save
        format.html { redirect_to cpanel_grid_path(@grid), notice: '保存成功' }
        format.json { render :show, status: :created, location: @grid }
      else
        format.html { render :new }
        format.json { render json: @grid.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @grid.update(grid_params)
        format.html { redirect_to cpanel_grid_path(@grid), notice: '保存成功' }
        format.json { render :show, status: :ok, location: @grid }
      else
        format.html { render :edit }
        format.json { render json: @grid.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @grid.destroy
    render js: 'CPANEL.Grids.DataTable.refresh();CPANEL.alert_success("删除成功");'
  end

  def modal
    respond_to do |format|
      format.html
      format.json { render json: GridsModalDatatable.new(view_context, current_admin) }
    end
  end

  private

  def set_grid
    @grid = Grid.find(params[:id])
  end

  def grid_params
    params.require(:grid).permit(:code, :name, :memo)
  end
end
